// window.app = {
// 	/**
// 	 * 和后端的 ChatMsg 聊天模型对象保持一致
// 	 * @param {Object} senderId
// 	 * @param {Object} receiverId
// 	 * @param {Object} msg
// 	 * @param {Object} msgId
// 	 */
// 	ChatMsg(senderId, receiverId, msg, msgId){
// 		this.senderId = senderId;
// 		this.receiverId = receiverId;
// 		this.msg = msg;
// 		this.msgId = msgId;
// 	},
//
// 	/**
// 	 * 构建消息 DataContent 模型对象
// 	 * @param {Object} action
// 	 * @param {Object} chatMsg
// 	 * @param {Object} extand
// 	 */
// 	DataContent(action, chatMsg, extand){
// 		this.action = action;
// 		this.chatMsg = chatMsg;
// 		this.extand = extand;
// 	}
// }()

/* window.app={

	isNotNull:function(str){
		if(str!=null||str!=""||str!=undefined){
			return true;
		}
		return false;
	}
} */

/**
 * 演示程序当前的 “注册/登录” 等操作，是基于 “本地存储” 完成的
 * 当您要参考这个演示程序进行相关 app 的开发时，
 * 请注意将相关方法调整成 “基于服务端Service” 的实现。
 **/
(function($, owner) {

	owner.nettyServerUrl="ws://120.79.250.78:8088/chat";
	//
	//owner.nettyServerUrl="ws://192.168.43.14:8088/chat";
	/**服务器地址
	 * @param {Object} loginInfo
	 * @param {Object} callback
	 */


	//owner.serverUrl="http://192.168.137.1:9898";
	owner.serverUrl="http://120.79.250.78:9898";
	//owner.serverUrl="http://192.168.43.14:9898";192.168.43.204
	//owner.serverUrl="http://192.168.3.39:9898";192.168.137.1
	//owner.serverUrl="http://192.168.0.104:9999";
	/**服务器地址
	 * @param {Object} loginInfo
	 * @param {Object} callback
	 */
	owner.imgServerUrl="http://120.79.250.78:9999/yang/";

	/**
	 * 获取应用本地配置
	 **/
	/* owner.setSettings = function(settings) {
		settings = settings || {};
		localStorage.setItem('$settings', JSON.stringify(settings));
	}; */

	owner.setSettings = function(settings) {
		settings = settings || {};
		plus.storage.setItem('$settings', JSON.stringify(settings));
	};
	/**
	 * 设置应用本地配置
	 **/
	/* owner.getSettings = function() {
		var settingsText = localStorage.getItem('$settings') || "{}";
		return JSON.parse(settingsText);
	}; */
	owner.getSettings = function() {
		var settingsText = plus.storage.getItem('$settings') || "{}";
		return JSON.parse(settingsText);
	};
	/**
	 * @param {Object} loginInfo
	 * @param {Object} callback
	 */
	owner.setGestureState=function(){
		var settings = owner.getSettings();
		settings.gestures = '';
		owner.setSettings(settings);

	};
	/**
	 * 用户登录
	 **/
	owner.login = function(loginInfo, callback) {
		callback = callback || $.noop;
		loginInfo = loginInfo || {};
		loginInfo.username = loginInfo.username || '';
		loginInfo.password = loginInfo.password || '';

		var settings = owner.getSettings();
		settings.gestures='none';
		owner.setSettings(settings)

		if (loginInfo.username.length < 2) {
			plus.nativeUI.closeWaiting();
			return callback('账号最短为 5 个字符');
		}
		if (loginInfo.password.length < 2) {
			plus.nativeUI.closeWaiting();
			return callback('密码最短为 6 个字符');
		}

		var cid=plus.push.getClientInfo().clientid;
		$.ajax(owner.serverUrl+'/login',{
			data:{
				username:loginInfo.username,
				password:loginInfo.password,
				cid:cid
			},
			dataType:'json',//服务器返回json格式数据
			type:'post',//HTTP请求类型
			timeout:10000,//超时时间设置为10秒；
			headers:{'Content-Type':'application/json'},
			success:function(data){
				console.log(JSON.stringify(data));
				//服务器返回响应，根据响应结果，分析是否登录成功；
				if(data.status==200){
					plus.nativeUI.closeWaiting();
					owner.showToast("登录成功");
					owner.setGlobeUserInfo(data.users);

					/* var chatlist=plus.webview.getWebviewById("chatlist.html");
					$.fire(chatlist,"chatlist-reflusher");

					var connection=plus.webview.getWebviewById("connection.html");
					$.fire(connection,"connection-reflusher"); */



					var selfWebView=plus.webview.getWebviewById("self.html");
					$.fire(selfWebView,"reflush");

					$.openWindow("index.html","index.html");
				}else{
					plus.nativeUI.closeWaiting();
					owner.errorToast(data.msg);
				}

			},
			error:function(xhr,type,errorThrown){
				//异常处理；
				console.log(type);
			}
		});
	};

	/**
	 * 新用户注册
	 **/
	owner.reg = function(regInfo, callback) {
		callback = callback || $.noop;
		regInfo = regInfo || {};
		regInfo.account = regInfo.account || '';
		regInfo.password = regInfo.password || '';
		regInfo.cid = regInfo.cid || '';
		/* var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
		if(!myreg.test(regInfo.cid))
		{
			return callback('手机号格式错误');
		} */
		if (regInfo.account.length < 2) {
			return callback('用户名最短需要 2 个字符');
		}
		if (regInfo.password.length < 2) {
			return callback('密码最短需要 2 个字符');
		}

		/* if (!checkEmail(regInfo.email)) {
			return callback('邮箱地址不合法');
		} */
		$.ajax(owner.serverUrl+'/registeruser',{
			data:{
				username:regInfo.account,
				password:regInfo.password,
				name:regInfo.name,
				cid:regInfo.cid
			},
			dataType:'json',//服务器返回json格式数据
			type:'post',//HTTP请求类型
			timeout:10000,//超时时间设置为10秒；
			headers:{'Content-Type':'application/json'},
			success:function(data){
				console.log(JSON.stringify(data));
				//服务器返回响应，根据响应结果，分析是否登录成功；
				if(data.success){

					owner.showToast("success");

					$.openWindow("logint.html","logint.html");
				}else{
					owner.errorToast(data.err);
				}

			},
			error:function(xhr,type,errorThrown){
				//异常处理；
				console.log(type);
			}
		});

	};
	/**
	 * 登录成功显示标识
	 * @param {Object} msg
	 */
	owner.showToast=function(msg){
		plus.nativeUI.toast(msg,{icon:"/img/success.png",verticalAlign:"center"})
	};

	/**
	 * 登录失败显示标识
	 * @param {Object} msg
	 */
	owner.errorToast=function(msg){
		plus.nativeUI.toast(msg,{icon:"/img/error.png",verticalAlign:"center"})
	},

		/**
		 * 设置全局用户信息
		 * @param {Object} users
		 */
		owner.setGlobeUserInfo=function(users){
			var userInfoStr=JSON.stringify(users);
			plus.storage.setItem("users",userInfoStr);
		},
		/**
		 * 获取全局用户信息
		 */
		owner.getGlobeUserInfo=function(){
			var userInfoStr=plus.storage.getItem("users");
			return JSON.parse(userInfoStr);
		},
		/**
		 * 登出后，移除用户全局对象
		 */
		owner.userLogout= function() {
			var settings = owner.getSettings();
			settings.gestures = "";
			settings="";
			owner.setSettings(settings);
			plus.storage.removeItem("users");
			plus.storage.removeItem("contactList");
		};

	/**
	 * 清除手势
	 */
	owner.clearGesture= function() {
		plus.storage.removeItem('$state');
	};
	/**
	 * 获取当前状态
	 **/
	/* owner.getState = function() {
		var stateText = localStorage.getItem('$state') || "{}";
		return JSON.parse(stateText);
	}; */

	owner.getState = function() {
		var stateText = plus.storage.getItem('$state')|| "{}";
		return JSON.parse(stateText);
	};

	/**
	 * 设置当前状态
	 **/
	/* owner.setState = function(state) {
		state = state || {};
		localStorage.setItem('$state', JSON.stringify(state));
		//var settings = owner.getSettings();
		//settings.gestures = '';
		//owner.setSettings(settings);
	}; */

	owner.setState = function(state) {
		state = state || {};
		plus.storage.setItem('$state', JSON.stringify(state));
		//var settings = owner.getSettings();
		//settings.gestures = '';
		//owner.setSettings(settings);
	};

	owner.setConnectionList=function(str){
		var connectionStr=JSON.stringify(str);

		plus.storage.setItem("contactList", connectionStr);
	};

	owner.getConnectionList=function(){
		var connectionStr = plus.storage.getItem("contactList");

		if (connectionStr=='') {
			return [];
		}

		if (connectionStr==null) {
			return [];
		}

		if (connectionStr==undefined) {
			return [];
		}

		return JSON.parse(connectionStr);
	};

	/**
	 * 和后端的枚举对应
	 */
	owner.CONNECT= 1, 	// 第一次(或重连)初始化连接
		owner.CHAT= 2, 		// 聊天消息
		owner.SIGNED= 3, 		// 消息签收
		owner.KEEPALIVE= 4, 	// 客户端保持心跳
		owner.PULL_FRIEND=5,	// 重新拉取好友


		/**
		 * 和后端的 ChatMsg 聊天模型对象保持一致
		 * @param {Object} senderId
		 * @param {Object} receiverId
		 * @param {Object} msg
		 * @param {Object} msgId
		 */
		owner.ChatMsg= function(senderId, receiverId, msg, msgId){
			this.senderId = senderId;
			this.receiverId = receiverId;
			this.msg = msg;
			this.msgId = msgId;
		},

		/**
		 * 构建消息 DataContent 模型对象
		 * @param {Object} action
		 * @param {Object} chatMsg
		 * @param {Object} extand
		 */
		owner.DataContent= function(action, chatMsg, extand){
			this.action = action;
			this.chatMsg = chatMsg;
			this.extand = extand;
		},

		/**
		 * 聊天历史记录
		 * @param {Object} myId
		 * @param {Object} friendId
		 * @param {Object} msg
		 * @param {Object} flag
		 */
		owner.saveChatHistory= function(myId,friendId,msg,flag){
			var me=this;
			var chatKey="chat-"+myId+"-"+friendId;
			var chatHistoryStr=plus.storage.getItem(chatKey);
			var chatHistoryStrInfo;
			if(chatHistoryStr!=null){
				chatHistoryStrInfo=JSON.parse(chatHistoryStr);
			}else{
				chatHistoryStrInfo=[];
			}

			//
			var siggleMsg=new me.chatHistory(myId, friendId, msg,flag);

			chatHistoryStrInfo.push(siggleMsg);

			plus.storage.setItem(chatKey,JSON.stringify(chatHistoryStrInfo));
		},
		/**
		 * 聊天历史记录
		 * @param {Object} myId
		 * @param {Object} friendId
		 * @param {Object} msg
		 * @param {Object} flag
		 */
		owner.saveUnReadChatNumber= function(myId,friendId,index){
			var me=this;
			var numberKey="number-"+myId+"-"+friendId;

			//
			plus.storage.setItem(numberKey,JSON.stringify(index));
		},
		owner.getUnReadChatNumber= function(myId,friendId){

			var numberKey="number-"+myId+"-"+friendId;
			var number=plus.storage.getItem(numberKey);
			var returnNumber;
			console.log(number);
			if(number==0){
				returnNumber='';
			}
			returnNumber=number;
			return returnNumber;
		},

		owner.getChatHistory= function(myId,friendId){
			var me=this;
			var chatKey="chat-"+myId+"-"+friendId;
			var chatHistoryStr=plus.storage.getItem(chatKey);
			var chatHistoryStrInfo;
			if(chatHistoryStr!=null){
				chatHistoryStrInfo=JSON.parse(chatHistoryStr);
			}else{
				chatHistoryStrInfo=[];
			}
			return chatHistoryStrInfo;
		},


		owner.chatHistory= function(myId, friendId, msg,flag){
			this.myId = myId;
			this.friendId = friendId;
			this.msg = msg;
			this.flag = flag;
		},
		/**
		 * 聊天记录的快照，仅仅保存每次和朋友聊天的最后一条消息
		 * @param {Object} myId
		 * @param {Object} friendId
		 * @param {Object} msg
		 * @param {Object} isRead
		 */
		owner.saveUserChatSnapshot=function(myId, friendId, sendTime, msg, isRead) {
			var me = this;
			var chatKey = "chat-snapshot" + myId;


			// 从本地缓存获取聊天快照的list
			var chatSnapshotListStr = plus.storage.getItem(chatKey);
			var chatSnapshotList;
			if (chatSnapshotListStr!=null) {
				// 如果不为空
				chatSnapshotList = JSON.parse(chatSnapshotListStr);
				// 循环快照list，并且判断每个元素是否包含（匹配）friendId，如果匹配，则删除
				for (var i = 0 ; i < chatSnapshotList.length ; i ++) {
					if (chatSnapshotList[i].friendId == friendId) {
						// 删除已经存在的friendId所对应的快照对象
						chatSnapshotList.splice(i, 1);
						break;
					}
				}
			} else {
				// 如果为空，赋一个空的list
				chatSnapshotList = [];
			}

			// 构建聊天快照对象
			var singleMsg = new me.ChatSnapshot(myId, friendId, sendTime, msg, isRead);

			// 向list中追加快照对象
			chatSnapshotList.unshift(singleMsg);

			plus.storage.setItem(chatKey, JSON.stringify(chatSnapshotList));
		},

		/**
		 * 获取用户快照记录列表
		 */
		owner.getUserChatSnapshot= function(myId) {
			var me = this;
			var chatKey = "chat-snapshot" + myId;
			// 从本地缓存获取聊天快照的list
			var chatSnapshotListStr = plus.storage.getItem(chatKey);
			var chatSnapshotList;
			if (chatSnapshotListStr!=null) {
				// 如果不为空
				chatSnapshotList = JSON.parse(chatSnapshotListStr);
			} else {
				// 如果为空，赋一个空的list
				chatSnapshotList = [];
			}

			return chatSnapshotList;
		},
		/**
		 * 快照对象
		 * @param {Object} myId
		 * @param {Object} friendId
		 * @param {Object} msg
		 * @param {Object} isRead	用于判断消息是否已读还是未读
		 */
		owner.ChatSnapshot= function(myId, friendId, sendTime , msg, isRead){
			this.myId = myId;
			this.friendId = friendId;
			this.sendTime=sendTime;
			this.msg = msg;
			this.isRead = isRead;
		},
		/**
		 * 根据用户id，从本地的缓存（联系人列表）中获取朋友的信息
		 * @param {Object} friendId
		 */
		owner.getFriendFromContactList= function(friendId) {
			var contactListStr = plus.storage.getItem("contactList");

			// 判断contactListStr是否为空
			if (contactListStr!=null) {
				// 不为空，则把用户信息返回
				var contactList = JSON.parse(contactListStr);
				for (var i = 0 ; i < contactList.length ; i ++) {
					var friend = contactList[i];
					if (friend.users.userId == friendId) {

						return friend;
						break;
					}
				}
			} else {
				// 如果为空，直接返回null
				return null;
			}
		},
		/**
		 * 标记未读消息为已读状态
		 * @param {Object} myId
		 * @param {Object} friendId
		 */
		owner.readUserChatSnapshot= function(myId, friendId) {
			var me = this;

			var chatKey = "chat-snapshot" + myId;
			// 从本地缓存获取聊天快照的list
			var chatSnapshotListStr = plus.storage.getItem(chatKey);
			var chatSnapshotList;
			if (chatSnapshotListStr!=null) {
				// 如果不为空
				chatSnapshotList = JSON.parse(chatSnapshotListStr);
				// 循环这个list，判断是否存在好友，比对friendId，
				// 如果有，在list中的原有位置删除该 快照 对象，然后重新放入一个标记已读的快照对象
				for (var i = 0 ; i < chatSnapshotList.length ; i ++) {
					var item = chatSnapshotList[i];
					if (item.friendId == friendId) {

						item.isRead = true;		// 标记为已读
						chatSnapshotList.splice(i, 1, item);	// 替换原有的快照
						break;
					}
				}
				// 替换原有的快照列表
				plus.storage.setItem(chatKey, JSON.stringify(chatSnapshotList));
			} else {
				// 如果为空
				return;
			}
		}




}(mui, window.app = {}));
